# -*- coding: utf-8 -*-

import json
import logging
import random

from api.treasure.model import TreasureLite
from common.treasure.model import TREASURE_STATUS, TREASURE_TYPE
from common.cache import redis_cache
from common.utils.api import page2offset
from common.treasure.db import get_user_treasure
from common.account.db.account import get_account


# 打开宝箱算法
def weighted_random(items):
    total = sum(w for _,w in items)
    n = random.uniform(0, total) # 在饼图扔骰子
    for x, w in items: # 遍历找出骰子所在的区间
        if n < w:
            break
        n -= w
    return x


def view_my_treasures(user_id, page, size):
    limit, offset = page2offset(page, size, max_size=30, default_size=20)
    if not page or page < 1:
        page = 1
    treasure_list = get_user_treasure(user_id, limit, offset)
    treasure_lites = []
    for box in treasure_list:
        treasure_lites.append(_create_treasure_lite(box))
    return treasure_lites


def _create_treasure_lite(treasure):
    account = get_account(treasure.user_id)
    treasure_lite = TreasureLite()
    treasure_lite.id = treasure.id
    treasure_lite.user_name = account.user_name[0] + '***' + account.user_name[-1]
    treasure_lite.status = treasure.status
    treasure_lite.amount = treasure.amount
    treasure_lite.date = treasure.date

    return treasure_lite